/**
 * Copyright 2010 Tristan Slominski
 *
 * Licensed under the MIT License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.opensource.org/licenses/mit-license.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mindash.handlebars.client.services.impl;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.inject.Inject;
import com.mindash.handlebars.client.services.EventBus;

/**
 * Implementation of the event bus that fires all the events in the order they
 * were received. (as opposed to immediately within the context of whatever
 * event is currently firing)
 * 
 * @author Tristan Slominski
 * 
 */
public class QueueingEventBusImpl extends HandlerManager implements EventBus {

  /* variables */
  private boolean busy = false;
  private List<GwtEvent<?>> queue = new ArrayList<GwtEvent<?>>();

  @Inject
  public QueueingEventBusImpl() {
    super(null);
  }

  /**
   * Executes the events in the queue.
   */
  public void execute() {
    // starts off in busy state, should get events from the queue and start
    // executing them
    while (!getQueue().isEmpty()) {
      super.fireEvent(getQueue().get(0));
      getQueue().remove(0);
    }
    // finished executing all events
    setBusy(false);
  }

  /**
   * Fires the event in the order received.
   * 
   * @param event the event to be fired;
   */
  @Override
  public void fireEvent(GwtEvent<?> event) {
    // check if busy
    if (isBusy()) {
      // we're busy executing another event, push this event on the queue
      getQueue().add(event);
    } else {
      // no event is being executed, push ourselves on the queue and start
      // executing
      setBusy(true);
      getQueue().add(event);
      execute();
    }
  }

  /* getters and setters */

  public void setBusy(boolean busy) {
    this.busy = busy;
  }

  public boolean isBusy() {
    return busy;
  }

  public void setQueue(List<GwtEvent<?>> queue) {
    this.queue = queue;
  }

  public List<GwtEvent<?>> getQueue() {
    return queue;
  }

}
